package com.pinapel.aixml.tools;

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.JTree;

import com.pinapel.aixml.tools.log.EnumMessageType;
import com.pinapel.aixml.tools.log.Logger;

public class Printer {
	/**
	 * Save the current tree in a file. file must be a valid file descriptor.
	 * 
	 * @param tree
	 * @param file
	 */
	public static void printTree(JTree tree, File imageOut) {

		try {
			// Expanding rows
			for (int i = 0; i < tree.getRowCount(); i++) {
				tree.expandRow(i);
			}

			BufferedImage image = new BufferedImage(tree.getWidth(),
					tree.getHeight(), BufferedImage.TYPE_INT_RGB);
			Graphics2D g = image.createGraphics();
			tree.paint(g);
			g.dispose();

			// File to save output Image
			Logger.addMessage(EnumMessageType.DEBUG_INFO, "Writing the image in file: "+ imageOut.getName());
			ImageIO.write(image, FileManager.getExtension(imageOut), imageOut);
		} catch (NullPointerException ex) {
			Logger.addMessage(EnumMessageType.DEBUG_ERROR,
					"Maybe tree params is null");
		} catch (IllegalArgumentException ex) {
			Logger.addMessage(EnumMessageType.DEBUG_INFO, "Canceled: " + ex.getMessage());
			ex.printStackTrace();
		} catch (IOException ex) {
			System.out.println(ex.getMessage());
		}
	}
}
